"""StatefulSet资源提取器模块"""

from typing import Dict, Any, Optional
import logging
from src.extractors.base import Extractor

class StatefulSetExtractor(Extractor):
    """
    StatefulSet资源提取器
    负责从StatefulSet资源定义中提取关键信息
    """
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        """初始化StatefulSet提取器"""
        super().__init__(logger)
        self.resource_type = "StatefulSet"
    
    def extract(self, content: str, file_path: str = "") -> Dict[str, Any]:
        """
        从StatefulSet YAML/JSON内容中提取信息
        
        Args:
            content: YAML/JSON格式的资源内容
            file_path: 资源文件路径，可选，用于日志记录
            
        Returns:
            提取的StatefulSet资源信息字典
        """
        # 解析YAML/JSON内容
        resource = self.parse_content(content, file_path)
        if not resource:
            return {}
        
        # 验证资源类型
        if resource.get("kind") != "StatefulSet":
            self.logger.warning(f"资源类型不是StatefulSet: {file_path}")
            return {}
        
        # 提取基本信息
        result = self._extract_basic_info(resource)
        
        # 提取StatefulSet特有信息
        spec = {}
        
        # 提取副本数
        if "spec" in resource and "replicas" in resource["spec"]:
            spec["replicas"] = resource["spec"]["replicas"]
        
        # 提取服务名称
        if "spec" in resource and "serviceName" in resource["spec"]:
            spec["serviceName"] = resource["spec"]["serviceName"]
        
        # 提取Pod管理策略
        if "spec" in resource and "podManagementPolicy" in resource["spec"]:
            spec["podManagementPolicy"] = resource["spec"]["podManagementPolicy"]
        
        # 提取更新策略
        if "spec" in resource and "updateStrategy" in resource["spec"]:
            update_strategy = resource["spec"]["updateStrategy"]
            strategy_info = {}
            
            if "type" in update_strategy:
                strategy_info["type"] = update_strategy["type"]
            
            if "rollingUpdate" in update_strategy:
                rolling_update = update_strategy["rollingUpdate"]
                rolling_info = {}
                
                if "partition" in rolling_update:
                    rolling_info["partition"] = rolling_update["partition"]
                
                if rolling_info:
                    strategy_info["rollingUpdate"] = rolling_info
            
            if strategy_info:
                spec["updateStrategy"] = strategy_info
        
        # 提取选择器
        if "spec" in resource and "selector" in resource["spec"]:
            spec["selector"] = resource["spec"]["selector"]
        
        # 提取模板信息
        if "spec" in resource and "template" in resource["spec"]:
            template = resource["spec"]["template"]
            template_info = {}
            
            # 提取模板元数据
            if "metadata" in template:
                metadata = template["metadata"]
                template_metadata = {}
                
                for key in ["labels", "annotations"]:
                    if key in metadata:
                        template_metadata[key] = metadata[key]
                
                if template_metadata:
                    template_info["metadata"] = template_metadata
            
            # 提取容器信息
            if "spec" in template:
                pod_spec = template["spec"]
                template_spec = {}
                
                # 提取容器列表
                if "containers" in pod_spec:
                    containers = []
                    for container in pod_spec["containers"]:
                        container_info = {}
                        for key in ["name", "image", "imagePullPolicy", "command", "args"]:
                            if key in container:
                                container_info[key] = container[key]
                        
                        # 提取资源请求和限制
                        if "resources" in container:
                            container_info["resources"] = container["resources"]
                        
                        # 提取环境变量
                        if "env" in container:
                            env_vars = []
                            for env in container["env"]:
                                env_info = {"name": env["name"]}
                                if "value" in env:
                                    env_info["value"] = env["value"]
                                elif "valueFrom" in env:
                                    env_info["value_from"] = self._clean_keys(env["valueFrom"])
                                env_vars.append(env_info)
                            container_info["env"] = env_vars
                        
                        # 提取端口
                        if "ports" in container:
                            ports = []
                            for port in container["ports"]:
                                port_info = {}
                                for port_key in ["containerPort", "name", "protocol"]:
                                    if port_key in port:
                                        port_info[port_key] = port[port_key]
                                ports.append(port_info)
                            container_info["ports"] = ports
                        
                        # 提取卷挂载
                        if "volumeMounts" in container:
                            volume_mounts = []
                            for mount in container["volumeMounts"]:
                                mount_info = {
                                    "name": mount.get("name", ""),
                                    "mount_path": mount.get("mountPath", "")
                                }
                                if "readOnly" in mount:
                                    mount_info["read_only"] = mount["readOnly"]
                                if "subPath" in mount:
                                    mount_info["sub_path"] = mount["subPath"]
                                volume_mounts.append(mount_info)
                            container_info["volume_mounts"] = volume_mounts
                        
                        containers.append(container_info)
                    
                    template_spec["containers"] = containers
                
                # 提取初始化容器
                if "initContainers" in pod_spec:
                    init_containers = []
                    for init_container in pod_spec["initContainers"]:
                        init_container_info = {}
                        for key in ["name", "image", "imagePullPolicy", "command", "args"]:
                            if key in init_container:
                                init_container_info[key] = init_container[key]
                        init_containers.append(init_container_info)
                    template_spec["initContainers"] = init_containers
                
                # 提取卷
                if "volumes" in pod_spec:
                    volumes = []
                    for volume in pod_spec["volumes"]:
                        volume_info = {"name": volume["name"]}
                        for volume_type in ["configMap", "secret", "persistentVolumeClaim", "emptyDir", "hostPath"]:
                            if volume_type in volume:
                                volume_info[volume_type] = volume[volume_type]
                        volumes.append(volume_info)
                    template_spec["volumes"] = volumes
                
                if template_spec:
                    template_info["spec"] = template_spec
            
            if template_info:
                spec["template"] = template_info
        
        # 提取卷声明模板
        if "spec" in resource and "volumeClaimTemplates" in resource["spec"]:
            volume_claim_templates = []
            for pvc in resource["spec"]["volumeClaimTemplates"]:
                pvc_info = {}
                
                # 提取元数据
                if "metadata" in pvc:
                    pvc_metadata = {}
                    for key in ["name", "labels", "annotations"]:
                        if key in pvc["metadata"]:
                            pvc_metadata[key] = pvc["metadata"][key]
                    if pvc_metadata:
                        pvc_info["metadata"] = pvc_metadata
                
                # 提取存储请求
                if "spec" in pvc:
                    pvc_spec = {}
                    for key in ["accessModes", "storageClassName", "volumeMode"]:
                        if key in pvc["spec"]:
                            pvc_spec[key] = pvc["spec"][key]
                    
                    # 提取存储大小
                    if "resources" in pvc["spec"] and "requests" in pvc["spec"]["resources"]:
                        if "storage" in pvc["spec"]["resources"]["requests"]:
                            pvc_spec["storage"] = pvc["spec"]["resources"]["requests"]["storage"]
                    
                    if pvc_spec:
                        pvc_info["spec"] = pvc_spec
                
                if pvc_info:
                    volume_claim_templates.append(pvc_info)
            
            if volume_claim_templates:
                spec["volumeClaimTemplates"] = volume_claim_templates
        
        result["spec"] = spec
        
        return result